package com.brainardphotography.blog.dao;

import java.util.List;
import java.util.logging.Logger;

import com.brainardphotography.blog.BlogUser;
import com.google.appengine.api.users.User;
import com.googlecode.objectify.NotFoundException;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class BlogUserDAO extends BaseDAO {
	private static final Logger log = Logger.getLogger(BlogUserDAO.class.getName());

	public List<BlogUser> findAll() {
		Objectify ofy = ObjectifyService.begin();

		return ofy.query(BlogUser.class).list();
	}

	public BlogUser get(String userId) {
		log.info("Looking up user: " + userId);
		Objectify ofy = ObjectifyService.begin();

		return ofy.get(BlogUser.class, userId);
	}
	
	/**
	 * Return a BlogUser with the User.getUserId() ID.
	 * @param user Google AppEngine User
	 * @return Null if user is null or a new BlogUser created from AppEngine User.
	 */
	public BlogUser get(User user) {
		return get(user, true);
	}

	/**
	 * Return a BlogUser with the User.getUserId() ID.
	 * @param user Google AppEngine User.
	 * @param create Flag that indicates this method should create a new BlogUser if one doesn't
	 * already exist.
	 * @return New user or null if create is false or user is null.
	 */
	public BlogUser get(User user, boolean create) {
		BlogUser buser = null;
		
		try {
			buser = get(user.getEmail());
		} catch (NotFoundException nfex) {
			if(create && user != null) {
				buser = BlogUser.withAppengineUser(user).build();
				save(buser);
			}
		}
		
		return buser;
	}

	/**
	 * Find user by e-mail address.
	 * 
	 * @param email
	 * @return User entity from the storage service.
	 * @throws EntityNotFoundException
	 *             if user record is not in the database.
	 */
	public BlogUser findByEmail(String email) throws EntityNotFoundException {
		Objectify ofy = ObjectifyService.begin();

		List<BlogUser> users = ofy.query(BlogUser.class)
				.filter("email =", email).list();

		if (users.size() > 1) {
			// TODO: Implement proper error handling for this situation.
			throw new RuntimeException("Too many results returned for " + email);
		}

		if (users.size() == 1)
			return users.get(0);

		throw new EntityNotFoundException(email,
				"Unable to find user with provided email: " + email);
	}

	public void save(BlogUser user) {
		log.info("Saving user: " + user);
		Objectify ofy = ObjectifyService.begin();

		ofy.put(user);
	}
}
